﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace BaseTool
{

    public class HttpHelper
    {
        /// <summary>
        /// Post
        /// </summary>
        /// <param name="url"></param>
        /// <param name="jsonData">json字符串</param>
        /// <returns></returns>
        public static string Post(string url, string jsonStr)
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
            request.KeepAlive = true;
            try
            {
                using (var streamWriter = new StreamWriter(request.GetRequestStream()))
                {
                    streamWriter.Write(jsonStr);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
                HttpWebResponse httpWebResponse = (HttpWebResponse)request.GetResponse();
                StreamReader streamReader = new StreamReader(httpWebResponse.GetResponseStream());
                string responseContent = streamReader.ReadToEnd();
                httpWebResponse.Close();
                streamReader.Close();
                return responseContent;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <param name="urlstr"></param>
        /// <returns></returns>
        public string Get(string urlstr)
        {
            try
            {
                using (var httpClient = new HttpClient())
                {
                    //get
                    var url = new Uri(urlstr);
                    // response
                    var response = httpClient.GetAsync(url).Result;
                    var data = response.Content.ReadAsStringAsync().Result;
                    return data;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }
    }
}
